package easier.nested.scroll;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.NestedScrollingParent2;
import androidx.core.view.NestedScrollingParentHelper;

/**
 * @author Liujin 2018-09-20:8:50
 */
public class TestNestedParentView extends FrameLayout implements NestedScrollingParent2 {

    private static final String TAG = TestNestedParentView.class.getSimpleName();
    private NestedScrollingParentHelper mParentHelper;

    public TestNestedParentView(
        @NonNull Context context ) {

        this( context, null, 0 );
    }

    public TestNestedParentView(
        @NonNull Context context,
        @Nullable AttributeSet attrs ) {

        this( context, attrs, 0 );
    }

    public TestNestedParentView(
        @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr ) {

        super( context, attrs, defStyleAttr );
        init();
    }

    private void init() {

        mParentHelper = new NestedScrollingParentHelper( this );
    }

    @Override
    public boolean onStartNestedScroll(
        @NonNull View child, @NonNull View target, int axes, int type ) {

        return true;
    }

    @Override
    public void onNestedScrollAccepted(
        @NonNull View child, @NonNull View target, int axes, int type ) {

        mParentHelper.onNestedScrollAccepted( child, target, axes, type );
    }

    @Override
    public void onStopNestedScroll( @NonNull View target, int type ) {

        mParentHelper.onStopNestedScroll( target, type );
    }

    @Override
    public void onNestedScroll(
        @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
        int type ) {

    }

    @Override
    public void onNestedPreScroll(
        @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type ) {

        if ( dx > 0 ) {
            int finalX = target.getRight() + dx;
            if ( finalX > getWidth() ) {
                int offsetX = finalX - getWidth();
                consumed[0] += offsetX;
                offsetLeftAndRight( offsetX );
            }
        } else {
            int finalX = target.getLeft() + dx;
            if ( finalX < 0 ) {
                offsetLeftAndRight( finalX );
                consumed[0] += finalX;
            }
        }

        if ( dy > 0 ) {
            int finalY = target.getBottom() + dy;
            if ( finalY > getHeight() ) {
                int offsetY = finalY - getHeight();
                offsetTopAndBottom( offsetY );
                consumed[1] += offsetY;
            }
        } else {

            int finalY = target.getTop() + dy;
            if ( finalY < 0 ) {
                offsetTopAndBottom( finalY );
                consumed[1] = finalY;
            }
        }
    }
}
